<template>
  <div class="divBox">
    <el-card class="box-card">
      <el-form inline size="small" @submit.native.prevent>
        <el-form-item label="年度：">
          <el-input v-model="listPram.year" placeholder="请输入年度" clearable class="selWidth"/>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" size="mini" type="primary" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button icon="el-icon-delete" type="danger" size="mini" @click="removeAll()"
            v-hasPermi="['admin:tests:record:deleteIds']">批量删除</el-button>
        </el-form-item>
        <el-form-item class="el-form-item-align-right">
          <el-button icon="el-icon-circle-plus" size="mini" type="primary" @click="handlerOpenEdit(0)" >添加</el-button>
          <el-button icon="el-icon-download" size="mini" type="primary" @click="handlerExport(1)"  style="margin-left:0;">批量导出</el-button>
          <el-upload
            class="upload-demo"
            style="display:inline-block!important;"
            action
            accept="application/xls,application/x-xls,application/zip,application/rar"
            :before-upload="onBeforeUpload"
            :http-request="handleUploadForm"
            :headers="myHeaders"
            :show-file-list="false"
          >
            <el-button icon="el-icon-upload2" size="mini" type="primary" >导入</el-button>
          </el-upload>
          <el-button icon="el-icon-download" size="mini" type="primary" @click="getMuBan('/试验记录.xls','试验记录导入模板')" style="margin-left:0;">导入模板下载</el-button>

        </el-form-item>
      </el-form>
      <el-table ref="multipleTable" :data="listData.list"  v-loading="loading" row-key="getRowKeys" @select="handleCheckBox" @select-all="handleSelectAll" size="mini"
                @sort-change="handleSortChange"
                :header-cell-style=" {fontWeight:'bold',background:'#f8f8f9',color: '#515a6e',height:'40px'}" border>
        <el-table-column
          type="selection"
          width="50"
        />
        <el-table-column
          prop="number"
          label="序号"
          width="50"
          sortable="custom"
        />
        <el-table-column label="年度" prop="year" min-width="120"/>
        <el-table-column label="型号" prop="modelUnit" min-width="120"/>
        <el-table-column label="试验类型" prop="testType" min-width="120"/>
        <el-table-column label="试验科目" prop="testSubject" min-width="120"/>
        <el-table-column label="试验日期" prop="testTime" min-width="120"/>
        <el-table-column label="试验条件" prop="testCondition" min-width="120"/>
        <el-table-column label="试验结果" prop="testResult" min-width="120"/>
        <el-table-column label="出现故障" prop="testFault" min-width="120"/>
        <el-table-column label="操作" min-width="210" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button icon="el-icon-edit" type="primary" size="mini" @click="handlerOpenEdit(1,scope.row)" >编辑</el-button>
            <el-button icon="el-icon-download" type="success" size="mini" @click="handlerExport(2,scope.row)" >导出</el-button>
            <el-button icon="el-icon-delete" type="danger" size="mini" @click="handlerOpenDel(scope.row)" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="listPram.page"
        :page-sizes="constants.page.limit"
        :layout="constants.page.layout"
        :total="listData.count"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <el-dialog
      :visible.sync="editDialogConfig.visible"
      :title="editDialogConfig.isCreate === 0? '添加':'编辑'"
      destroy-on-close
      :close-on-click-modal="false"
      width="1300px"
    >
      <edit
        v-if="editDialogConfig.visible"
        :is-create="editDialogConfig.isCreate"
        :id="editDialogConfig.id"
        :all-tree-list="treeList"
        :all-category-data="categoryData"
        @hideEditDialog="hideEditDialog"
      />
    </el-dialog>
  </div>
</template>

<script>
import edit from '@/views/tests/recordEdit'
import { checkPermi } from "@/utils/permission";
import * as selfUtil from "@/utils/ZBKJIutil";
import { createFile, exportTest } from '@/utils/utils'
import {getToken} from "@/utils/auth";
import * as testsApi from '@/api/tests'
import * as categoryApi from "@/api/categoryApi";
import { deleteTestsRecordApi } from '@/api/tests'
export default {
  components: { edit },
  data() {
    return {
      constants:this.$constants,
      loading:false,
      listData: { list: [] },
      listPram: {
        year: '',
        /*departmentId: null,
        ipAddress: null,
        macAddress: null,
        personId: null,*/
        page: 1,
        limit: this.$constants.page.limit[0]
      },
      editDialogConfig: {
        visible: false,
        isCreate: 0, // 0=创建，1=编辑
        editData: {},
        id: 0,
      },
      treeList:[],
      categoryData:{},

      myHeaders: { "X-Token": getToken() },

      multipleSelection: [],//勾选的人员对象ID
    }
  },
  mounted() {
    this.handleGetPointList()
    this.handlerGetTreeList() //所属单位
  },
  methods: {
    handleSortChange(c) {
      const order = c.order;
      if (order == null || order == 'ascending') {
        this.listPram.sortType = 2;
      } else {
        this.listPram.sortType = 1;
      }
      this.handleGetPointList();
    },
    checkPermi,
    handleSearch() {
      this.listPram.page = 1
      this.handleGetPointList()
    },
    handleSizeChange(val) {
      this.listPram.limit = val
      this.handleGetPointList()
    },
    handleCurrentChange(val) {
      this.listPram.page = val
      this.handleGetPointList()
    },
    handlerOpenDel(rowData) {
      this.$confirm('确认删除当前数据').then(() => {
        const _pram = { id: rowData.id}
        testsApi.deleteTestsRecordApi(_pram).then(data => {
          this.$message.success('删除数据成功')
          this.handleGetPointList()
        })
      })
    },

    //获取部门列表
    handlerGetTreeList() {
      const _pram = { name: '' }
      this.loading = true
      categoryApi.treeCategroy(_pram, 3).then(data => {
        this.treeList = this.handleAddArrt(data)
        this.loading = false
      }).catch(()=>{
        this.loading = false
      })
    },
    handleAddArrt(treeData) {
      const _result = selfUtil.addTreeListLabel(treeData)
      return _result
    },
    handleGetPointList() {
      testsApi.getTestsRecordListApi( this.listPram ).then(data => {
        this.listData = data
      })
    },
    handlerOpenEdit(isCreate, editDate) {
      if(editDate)
      {
        this.editDialogConfig.id = editDate.id
      }
      this.editDialogConfig.isCreate = isCreate
      this.editDialogConfig.visible = true
    },
    hideEditDialog() {
      this.editDialogConfig.visible = false
      this.handleGetPointList()
    },
    resetQuery(){
      this.listPram.year = '';
      this.handleGetPointList()
    },
    getMuBan(url,fileName)
    {
      exportTest(url,fileName);
    },
    //导入
    onBeforeUpload(file) {
      const isEXCEL = file.type === 'application/xls'||'application/x-xls'||'application/zip'||'application/rar';
      const isLt1M = file.size / 1024 / 1024 < 100;

      if (!isEXCEL) {
        this.$message.error('上传文件只能是EXCEL格式!');
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 100MB!');
      }
      return isEXCEL && isLt1M;
    },
    // 上传
    handleUploadForm(param) {
      const formData = new FormData();
      formData.append("file", param.file);
      let loading = this.$loading({
        lock: true,
        text: "上传中，请稍候...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      testsApi.doImport(formData)
        .then((res) => {

          let msg = "";
          if (res[0]) {
            msg = res[0];
            this.$message.error(msg);
          }else{
            msg = "保护点信息导入成功";
            this.$message.success(msg);
          }
          loading.close();

          this.handleGetPointList()
        })
        .catch((res) => {
          loading.close();
        });
    },


    //导出
    handlerExport(operateType,editData) {
      if(operateType === 1 && this.multipleSelection.length === 0){
        this.$message.error("请在列表中勾选导出项")
        return
      }
      let loading = this.$loading({
        lock: true,
        text: "导出中，请稍候...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      let ids = ''
      if(operateType === 2){
        ids = editData.id
      }else{
        ids =  this.multipleSelection.join(',')
      }
      const _pram = {ids: ids}
      testsApi.exportRoster(_pram)
        .then((res) => {
          if(!createFile(res,'试验记录')){
            this.$message.success("未知的文件格式");
          }

          loading.close();
        })
        .catch((res) => {
          loading.close();
        });
    },  //勾选/取消
  handleCheckBox(rows, row) {
      var index = this.multipleSelection.indexOf(row.id);
      if (index !== -1) {
        this.multipleSelection.splice(index, 1);
      } else {
        this.multipleSelection.push(row.id);
      }
    },
    //全部勾选/取消
    handleSelectAll(rows) {
      this.multipleSelection = []; // 清空数组
      if (rows.length > 0) {
        rows.forEach((row) => {
          this.multipleSelection.push(row.id);
        });
      } else {
        this.listData.list.forEach((row) => {
          this.multipleSelection = this.multipleSelection.filter(
            (item) => item != row.id
          )
        })
      }
    }
    ,
    //批量删除
    removeAll() {
      // 将 this.multipleSelection 赋值给变量 selectedIds
      // 弹出确认对话框并发送删除请求
      if (this.multipleSelection.length == 0) {
        this.$message.warning('请至少选择一条要删除的数据');
        return;
      }
      this.$confirm("确认要删除选中的" + this.multipleSelection.length + "条数据吗?").then(() => {
        const loading = this.$loading({ text: '删除中' });
        testsApi.typeDelBatchTestsRecord({ ids: this.multipleSelection.join(',') }).then(() => {
          this.$message.success('删除成功');
          this.listPram.page = 1;
          this.handleGetPointList();
        }).finally(() => {
          loading.close();
        })
      })
    },
    //下面的方法是进行设置行标识key的方法
    getRowKeys(row) {
      return row.id
    },
    toggleSelection() {
      this.$refs.multipleTable.clearSelection();
    }
  }
}
</script>

<style scoped>

</style>
